﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using CVS.DAL;

namespace CVS.Gateway
{
    public class CvsGateway : ICsvGateway
    {
        public List<Submission> GetPendingSubmissions()
        {
            using (var context = new CodeVerificationSystemEntities())
            {
                var fiveSecondsAgo = DateTime.Now.AddSeconds(-5);
                return
                    context.Submissions.Where(
                        s =>
                            s.IsProcessed == false &&
                            (s.ProcessingStartTime == null || s.ProcessingStartTime < fiveSecondsAgo))
                                          .Include(s => s.CompilationResult)
                                          .Include(s => s.TestRuns).ToList();
            }
        }

        public List< TestDefinition > GetTestDefinitionsForSubmission( Submission submission )
        {
            using (var context = new CodeVerificationSystemEntities())
            {
                return context.TestDefinitions.Where( t => t.TaskId == submission.TaskId ).ToList( );
            }
        }

        public void AddCompilationResult(CompilationResult compilationResult)
        {
            using (var context = new CodeVerificationSystemEntities())
            {
                context.CompilationResults.Add(compilationResult);
                context.SaveChanges();
            }
        }

        public void AddTestRuns(List<TestRun> testRuns)
        {
            using (var context = new CodeVerificationSystemEntities())
            {
                foreach ( var testRun in testRuns )
                {
                    context.TestRuns.Add( testRun );
                }

                context.SaveChanges( );
            }
        }
    }
}
